import {
	defineStore
} from 'pinia'
import * as API from "../api/api.js"
import * as TextEncoding from "text-encoding-shim";
export const useChatStore = defineStore('useChat', {
	state: () => {
		return {
      userInfo: null,
      extraData: null,
      path: null,
      allContent: "",
      showContent: false,
      str: "",
      p: 0,
      sseEnd: false
		}
	},
	actions: {
    setShowContent(value) {
      this.showContent = value
    },
    setAllContent(value) {
      this.allContent = value
    },
    initPresetQuestion() {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      return API.initPresetQuestion({userId: this.userInfo?.customers?.customerId}).then(res => {
        if (res.code === 0) {
          console.log("初始化成功")
        }
      }).catch(err => {

      })
    },
    listPresetQuestion() {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      return new Promise((resolve, reject) => {
        API.listPresetQuestion({userId: this.userInfo?.customers?.customerId}).then(res => {
          if (res.code === 0) {
            resolve(res.data)
          }
        }).catch(err => {
  
        })
      })
    },

    getRobotMsg: function (query) {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      const _this = this
      _this.sseEnd = false
      _this.allContent = ""
      let params = {
        userId: this.userInfo?.customers?.customerId, //用户id
        age: this.userInfo?.customers?.age, //年龄
        weight: this.userInfo?.customers?.weight, //体重
        height: this.userInfo?.customers?.height, //身高
        gender: this.userInfo?.customers?.gender == 1 ? "男" : "女", //性别
        timeType: query.timeType, //类型 0：开跑前 1：暂停 2：结束
        uuid: query.uuid, //uuid
        duration: query.duration || null,
        distance: query.distance || null,
        pace: query.pace || null
      };
      console.log("params===", params, query)
      const requestTask = uni.request({
        url: API.promptTrick,
        data: params,
        method: "POST",
        enableChunked: true,
        success: (response) => {
        },
        fail: (err) => {
          console.log("sse链接失败");
          _this.sseEnd = true
        },
        complete: function () {
          console.log("sse对接结束")
          _this.sseEnd = true
        },
      });

      requestTask.onChunkReceived((chunk) => {
        this.showContent = true
        const arrayBuffer = chunk.data;
        const uint8Array = new Uint8Array(arrayBuffer);
        const decodeBase64Str = new TextEncoding.TextDecoder("utf-8").decode(uint8Array);
        this.str += decodeBase64Str;
        this.decodeFn();
      });
    },

    parseStr(str) {
      const _this = this;
      const _str = str.substring(5);
      try {
        const message = JSON.parse(_str);
        if (message.code == 0) {
          if (!message.endFlag) {
            this.allContent += message.content   
          }
        }
      } catch (err) {
        console.log(err);
      }
    },

    decodeFn() {
      while (this.str.indexOf("data:", this.p) !== -1) {
        let line = "";
        const nextIndex = this.str.indexOf("data:", this.p);
        line = this.str.substring(this.p - 1, nextIndex);
        this.p = nextIndex + 1; // 移动到下一个字符
        if (line.trim()) {
          this.parseStr(line);
        }
      }
    },
  }
})

